package org.example.filter;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.pojo.Result;
import org.example.utils.JwtUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {
    @Override // 初始化 只会调用一次
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("拦截到了请求");
        // 将servletRequest和servletResponse进行强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取请求的url
        String url = request.getRequestURI();
        // 判断URL是否是login直接放行
        if (url.contains("login") || url.contains("register")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {
            Result err = Result.clientError("NOT_LOGIN");
            // 手动奖对象转化为json
            String notLogin  = JSONObject.toJSONString(err);
            response.getWriter().write(notLogin);
            return;
        }

        try {
            JwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            Result err = Result.clientError("NOT_LOGIN");
            // 手动奖对象转化为json
            String notLogin  = JSONObject.toJSONString(err);
            response.getWriter().write(notLogin);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override // 销毁方法 只会输出一次
    public void destroy() {
        Filter.super.destroy();
    }
}
